//
//  DRBindDeviceVC.m
//  DoctorRen
//
//  Created by Macx on 2018/11/21.
//

#import "DRBindDeviceVC.h"
#import "DRBluetoothManager.h"
#import "QNBleApi.h"
#import "DRLoginDataModel.h"
#import "OSZDataTool.h"

@interface DRBindDeviceVC ()<QNBleConnectionChangeListener,QNDataListener,QNBleDeviceDiscoveryListener,QNBleStateListener, DRBluetoothDelegate>
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;

@property (nonatomic, assign) DeviceStyle currentStyle;
@property (nonatomic, strong) QNBleApi *bleApi;
@property (nonatomic, strong) QNConfig *config;
@property (nonatomic, strong) QNBleDevice *currentDevice;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *connectingIV;
@property (weak, nonatomic) IBOutlet UIImageView *deviceImageView;
@property (weak, nonatomic) IBOutlet UILabel *unitCNLabel;
@property (weak, nonatomic) IBOutlet UILabel *unitENLabel;
@property (weak, nonatomic) IBOutlet UIView *unitView;
@property (weak, nonatomic) IBOutlet UILabel *valueLabel;

@property (nonatomic, strong) DRBluetoothManager *manager;
@end

@implementation DRBindDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //体重秤
    if (self.type == 0) {
        [self registerQNSDK];
        self.bleApi = [QNBleApi sharedBleApi];
        self.config = [self.bleApi getConfig];
        self.bleApi.discoveryListener = self;
        self.bleApi.connectionChangeListener = self;
        self.bleApi.dataListener = self;
        self.bleApi.bleStateListener = self;
        self.statusLabel.text = @"请开启体重秤";
        self.titleLabel.text = @"智能体重秤";
        self.unitCNLabel.text = @"体重";
        self.unitENLabel.text = @"KG";
        self.deviceImageView.image = [UIImage imageNamed:@"电子秤"];
        [self.closeBtn setTitle:@"关闭体重测量" forState:(UIControlStateNormal)];
        [self.startBtn setTitle:@"启动体重测量" forState:(UIControlStateNormal)];
        [self.startBtn sendActionsForControlEvents:(UIControlEventTouchUpInside)];
        ///** 同一个设备是否返回多次，默认为false */
//        self.config.allowDuplicates = NO;
        self.currentStyle = DeviceStyleScanning;
    }else{
        self.manager = [DRBluetoothManager manager];
        self.manager.delegate = self;
        if (self.type == 1) {
            self.statusLabel.text = @"请开启血糖仪";
            self.titleLabel.text = @"智能血糖仪";
            self.unitCNLabel.text = @"血糖值";
            self.unitENLabel.text = @"mmol/L";
            self.deviceImageView.image = [UIImage imageNamed:@"血糖仪"];
            [self.closeBtn setTitle:@"关闭血糖测量" forState:(UIControlStateNormal)];
            [self.startBtn setTitle:@"启动血糖测量" forState:(UIControlStateNormal)];
            [self.manager startConnectWithName:@"Bioland-BGM" serviceUUID:@"1000" characteristicUUID:@"1002" needWriteData:YES];
        }else{
            self.statusLabel.text = @"请开启血压仪";
            self.titleLabel.text = @"智能血压仪";
            self.unitCNLabel.text = @"血压值";
            self.unitENLabel.text = @"mmHg";
            self.deviceImageView.image = [UIImage imageNamed:@"血压计"];
            [self.closeBtn setTitle:@"关闭血压测量" forState:(UIControlStateNormal)];
            [self.startBtn setTitle:@"启动血压测量" forState:(UIControlStateNormal)];
            [self.manager startConnectWithName:@"Bioland-BPM" serviceUUID:@"1000"  characteristicUUID:@"1002" needWriteData:NO];
        }

    }
    
}

-(void) registerQNSDK{
    QNConfig *config = [[QNBleApi sharedBleApi] getConfig];
    config.showPowerAlertKey = YES;
    
    QNBleApi.debug = YES;
    NSString *file = [[NSBundle mainBundle] pathForResource:@"123456789" ofType:@"qn"];
    [[QNBleApi sharedBleApi] initSdk:@"123456789" firstDataFile:file callback:^(NSError *error) {
        
    }];
}


- (IBAction)clickCloseButton:(UIButton *)sender {
    
    if (self.type == 0) {
        [self stopScanDevice];
        
    }else{
        [self.manager endConnect]; 
    }
    if (self.block) {
        self.block(self.type, self.valueLabel.text);
    }
    [self dismissViewControllerAnimated:true completion:nil];
}


- (IBAction)cliclStartButton:(UIButton *)sender {
    if (self.type == 0) {
        self.currentStyle = DeviceStyleScanning;
    }else if (self.type == 1){
        [self.manager startConnectWithName:@"Bioland-BGM" serviceUUID:@"1000" characteristicUUID:@"1002" needWriteData:YES];
    }else{
        [self.manager startConnectWithName:@"Bioland-BPM" serviceUUID:@"1000"  characteristicUUID:@"1002" needWriteData:NO];
    }
}

-(void )setbluetoolConnectSuccess:(BOOL) isSuccess{
    self.connectingIV.hidden = isSuccess;
    self.statusLabel.hidden = isSuccess;
    
    self.deviceImageView.hidden = !isSuccess;
    self.unitView.hidden = !isSuccess;
    self.unitENLabel.hidden = !isSuccess;
    self.unitCNLabel.hidden = !isSuccess;
}

#pragma mark 设置设备各个阶段状态
- (void)setCurrentStyle:(DeviceStyle)currentStyle {
    _currentStyle = currentStyle;
    switch (_currentStyle) {
        case DeviceStyleScanning: //正在扫描
            self.statusLabel.text = @"正在扫描设备，请打开设备！";
            [self setbluetoolConnectSuccess:NO];
            if (self.type == 0) {
                [self startScanDevice];
            }
            break;
        case DeviceStyleLinging: //正在链接
            self.statusLabel.text = @"正在连接蓝牙";
            [self setbluetoolConnectSuccess:NO];
            break;
        case DeviceStyleLingSucceed: //链接成功
            self.statusLabel.text = @"蓝牙连接成功";
            [self setbluetoolConnectSuccess:YES];
            break;
        case DeviceStyleMeasuringWeight: //测量体重
//            self.statusLabel.text = @"正在称量";
            [self setbluetoolConnectSuccess:YES];
            break;
        case DeviceStyleMeasuringResistance: //测量阻抗
            break;
        case DeviceStyleMeasuringHeartRate: //测量心率
            break;
        case DeviceStyleMeasuringSucceed://测量完成
            break;
        case DeviceStyleDisconnect://断开连接/称关机
            self.statusLabel.text = @"断开连接";
            if (self.type == 0) {
                [self disconnectDevice];
            }
            break;
        default: //默认状态
            self.statusLabel.text = @"未连接设备";
            if (self.type == 0) {
                [self disconnectDevice];
            }
            break;
    }
}
#pragma mark - 蓝牙状态处理
#pragma mark 开始扫描附近设备
- (void)startScanDevice {

    [_bleApi startBleDeviceDiscovery:^(NSError *error) {
        NSLog(@"错误：%@",error.localizedDescription);
    }];
}

#pragma mark 链接设备设备
- (void)connectDevice:(QNBleDevice *)device {
    [_bleApi stopBleDeviceDiscorvery:^(NSError *error) {
        NSLog(@"connectDevice错误：%@",error.localizedDescription);
    }];
}

#pragma mark 断开设备
- (void)disconnectDevice {
    [_bleApi disconnectDevice:nil callback:^(NSError *error) {
        NSLog(@"disconnectDevice错误：%@",error.localizedDescription);
    }];
}

#pragma mark 停止扫描附近设备
- (void)stopScanDevice {
    [_bleApi stopBleDeviceDiscorvery:^(NSError *error) {
        NSLog(@"stopBleDeviceDiscorvery错误：%@",error.localizedDescription);
    }];
}

#pragma mark - QNBleDeviceDiscorveryListener
- (void)onDeviceDiscover:(QNBleDevice *)device {//该方法会在发现设备后回调
    if (!self.currentDevice ) {
        self.currentDevice = device;
        [_bleApi stopBleDeviceDiscorvery:^(NSError *error) {
            
        }];
        self.currentStyle = DeviceStyleLinging;
        DRUserModel *userModel = [DRLoginDataModel getUserModel];
        int height = [userModel.height integerValue] >= 40 ? [userModel.height integerValue]: 170;
        NSTimeInterval time = userModel.birthday ?: 974907993 ;
        QNUser *user = [self.bleApi buildUser:userModel.token height:height gender:userModel.sex == 0 ? @"female":@"male" birthday:[NSDate dateWithTimeIntervalSince1970:time] callback:^(NSError *error) {
            
        }];
        [self.bleApi connectDevice:self.currentDevice user:user callback:^(NSError *error) {
            
        }];
    }

}

#pragma mark - QNBleConnectionChangeListener
- (void)onScaleStateChange:(QNBleDevice *)device scaleState:(QNScaleState)state{//秤连接或测量状态变化
    if (state == QNScaleStateConnected) {//链接成功
        self.currentStyle = DeviceStyleLingSucceed;
        NSLog(@"秤连接或测量状态变化:连接成功");
    }else if (state == QNScaleStateRealTime){//测量体重
        self.currentStyle = DeviceStyleMeasuringWeight;
        NSLog(@"秤连接或测量状态变化:测量体重");
    }else if (state == QNScaleStateBodyFat){//测量阻抗
        self.currentStyle = DeviceStyleMeasuringResistance;
    }else if (state == QNScaleStateHeartRate){//测量心率
        self.currentStyle = DeviceStyleMeasuringHeartRate;
    }else if (state == QNScaleStateMeasureCompleted){//测量完成
        self.currentStyle = DeviceStyleMeasuringSucceed;
        NSLog(@"秤连接或测量状态变化:测量完成");
    }else if (state == QNScaleStateLinkLoss){//断开连接/称关机
        self.currentStyle = DeviceStyleNormal;
        NSLog(@"秤连接或测量状态变化:断开连接/称关机");
    }
}

#pragma mark - 测量QNDataListener处理
- (void)onGetUnsteadyWeight:(QNBleDevice *)device weight:(double)weight {
    weight = [self.bleApi convertWeightWithTargetUnit:weight unit:[self.bleApi getConfig].unit];
    self.valueLabel.text = [NSString stringWithFormat:@"%.1f",weight];
}

- (void)onGetScaleData:(QNBleDevice *)device data:(QNScaleData *)scaleData {
//    [self.scaleDataAry removeAllObjects];
//    for (QNScaleItemData *item in [scaleData getAllItem]) {
//        [self.scaleDataAry addObject:item];
//    }
//    [self.tableView reloadData];
    NSLog(@"%@",scaleData);
}

- (void)onGetStoredScale:(QNBleDevice *)device data:(NSArray<QNScaleStoreData *> *)storedDataList {
    
    
}

#pragma mark - QNBleStateListener
- (void)onBleSystemState:(QNBLEState)state {
    
}

#pragma mark - DRBluetoothManagerDelegate

-(void)didUpdateDevice:(DeviceStyle)style{
    self.currentStyle = style;
}

-(void)receivedValue:(NSData *)data{
    NSLog(@"收到的数据%@",data);
    // 这里收到的数据都是16进制，有两种转换，一种就直接转字符串，另一种是转byte数组，看用哪种方便
    Byte * resultByte = (Byte *)[data bytes];
    for (int i = 0; i < [data length]; i++) {
        NSLog(@"Byte [%d] = %d \n",i ,resultByte[i]);
    }
    
    if (self.type == 1) {
        //长度：12为结果包 5为结束包
        //以mg/dL单位上传测量结果，转为mmoL单位显示时必需除以18，并四舍五入。
        if ([data length] == 12) {
            //9和10为测量结果
            NSString *hexString = [NSString stringWithFormat:@"%@%@",[[NSString alloc]initWithFormat:@"%02lx",(long)resultByte[10]],[[NSString alloc]initWithFormat:@"%02lx",(long)resultByte[9]]];
            int intValue = [[OSZDataTool sharedTool] hexNumberStringToNumber:hexString];
            float value = ((intValue / 18.0) * 100 + 0.5) / 100;
            self.valueLabel.text = [NSString stringWithFormat:@"%.1f",value];
        }
    }else if (self.type == 2){
        //长度: 8过程包 14为结果包 5为错误包
        if ([data length] == 8) {
            //5 为事实压力
            self.valueLabel.text = [NSString stringWithFormat:@"%d",resultByte[5] + resultByte[6]];
        }else if ([data length] == 14){
            //高压9 低压11 脉搏12
            self.valueLabel.text= [NSString stringWithFormat:@"%d/%d",resultByte[9],resultByte[11]];
        }else if ([data length] ==5 ){
            [SVProgressHUD showErrorWithStatus:@"数据读取失败"];
        }
    }
    
}



@end
